/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pig.goods.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.goods.entity.TbCar;
import com.pig4cloud.pig.goods.entity.TbItem;
import com.pig4cloud.pig.goods.service.TbCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;


/**
 * 
 *
 * @author pig code generator
 * @date 2021-07-19 19:21:45
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tbcar" )
@Api(value = "tbcar", tags = "管理")
public class TbCarController {

	@Autowired
    private final  TbCarService tbCarService;

	@Resource(name = "redisCacheTemplate")
	private RedisTemplate redisTemplate;

    /**
     * 分页查询
     * @param page 分页对象
     * @param tbCar 
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('car_tbcar_get')")
    public Object getTbCarPage(Page page, TbCar tbCar) {
    	ArrayList<String> list = new ArrayList();
		PigUser user = SecurityUtils.getUser();
		Integer uid = user.getId();
		Set<String> keys = redisTemplate.opsForHash().keys("car");
		/*截取到商品id*/
		for (String key : keys){
			int i = key.indexOf(",");
			String substring = key.substring(0, i);
			System.out.println(substring);
			/*将所有的商品id存入到list中*/
			list.add(substring);
		}

		/*创建一个用于存放信息的集合*/
		List list1 = new ArrayList();

		/*根据商品id查询出购物车中的商品*/
		for (String o : list) {
			int i = Integer.parseInt(o);
			list1.add(tbCarService.carList(i).get(0));
		}
		System.out.println(list1);
		return list1;
	}


    /**
     * 通过id查询
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('car_tbcar_get')" )
    public R getById(@PathVariable("id" ) Integer id) {
        return R.ok(tbCarService.getById(id));
    }

    /**
	 * 新增
	 * @param
	 * @return R
	 */
	@ApiOperation(value = "新增", notes = "新增")
	@SysLog("新增" )
	@PostMapping
	@PreAuthorize("@pms.hasPermission('car_tbcar_add')" )
	public Boolean save(@RequestBody TbItem tbItem) {

		/*Long id = tbItem.getId();
		String s = id.toString();
		HashMap<String, Object> map = new HashMap<>();
		map.put(s,tbItem.getNum());
		redisTemplate.opsForHash().putAll("ms_goods",map);
		return true;*/
		System.out.println(tbItem);
		tbItem.setNum(1);
		//*首先获取到登录用户的id*//*
		PigUser user = SecurityUtils.getUser();
		Integer uid = user.getId();
		Boolean car = redisTemplate.opsForHash().putIfAbsent("car", tbItem.getId()+","+uid, tbItem.getId()+","+uid);
		if(car==true){
			redisTemplate.opsForHash().put("car",tbItem.getId()+","+uid,1);
			return true;
		}
		return false;
		/*首先获取到用户的id值*/
		/*PigUser user = SecurityUtils.getUser();
		Integer uid = user.getId();
		//展示购物车
		*//*获取到redis中的所有key的值*//*
		Set<String> keys = redisTemplate.opsForHash().keys("*");
		*//*遍历所有获取到的key值*//*
		for (String key : keys) {
			*//*用逗号进行分割*//*
			int i = key.indexOf(",");
			*//*获取到分割后的Id值（用户id）*//*
			String substring = key.substring(0, i);
			*//*查询出当前登录的用户*//*
			if(substring.equals(user.getId())){
				*//*获取到每一个key*//*
				Map<String,Object> o = (Map<String,Object>)redisTemplate.opsForValue().get(key);
				*//*遍历每一个Key*//*
				Set<Map.Entry<String, Object>> entries = o.entrySet();
				*//**//*
				for (Map.Entry<String, Object> entry : entries) {
					String key1 = entry.getKey();
					if(key1.equals("gid")){
						Object value = entry.getValue();
					}
				}
			}
		}

		*//*以商品id+用户id作为唯一标识*//*
		String carid=tbCar.getGid()+""+uid;

		*//*该用户存在该商品，就在原有基础上进行自增操作*//*
		if(redisTemplate.hasKey(carid)){
			redisTemplate.opsForHash().increment(carid,"num",1);
		}else{
			*//*如果*//*
			HashMap<String, Object> hashMap = new HashMap();
			Object u = JSON.parse(uid+"");
			Object g = JSON.parse(tbCar.getGid()+"");
			Object n = JSON.parse(1+"");
			hashMap.put("uid",u);
			hashMap.put("gid",g);
			hashMap.put("num",n);
			redisTemplate.opsForHash().putAll(carid,hashMap);
		}
		return true;*/
	}

	/**
	 * 初始化秒杀数据
	 * @param
	 * @return R
	 */
	/*@ApiOperation(value = "新增", notes = "新增")
	@SysLog("新增" )
	@PostMapping
	@PreAuthorize("@pms.hasPermission('car_tbcar_init')" )
	public void initMiaosha(@RequestBody TbItem tbItem) {
		Long id = tbItem.getId();
		String s = id.toString();
		HashMap<String, Object> map = new HashMap<>();
		map.put(s,10);
		redisTemplate.opsForHash().putAll("ms_goods",map);

	}*/

    /**
     * 修改
     * @return R
     */
    @ApiOperation(value = "秒杀")
    @SysLog("秒杀" )
    @PostMapping("/miaosha")
    @PreAuthorize("@pms.hasPermission('car_tbcar_edit')" )
	@Transactional
    public Object updateById(@RequestBody TbItem tbItem) {

		System.out.println(tbItem);

		Long id = tbItem.getId();
		String ms_key = id.toString();
		redisTemplate.setEnableTransactionSupport(true);

		Map msGoods = redisTemplate.opsForHash().entries("ms_goods");
		Integer num = (Integer) msGoods.get(ms_key);

		redisTemplate.multi();

		if(num>0){
			redisTemplate.opsForHash().increment("ms_goods", ms_key, -1);

		}
		redisTemplate.exec();

		return num;

    }

    /**
     * 通过id删除
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除", notes = "通过id删除")
    @SysLog("通过id删除" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('car_tbcar_del')" )
    public R removeById(@PathVariable Integer id) {
        return R.ok(tbCarService.removeById(id));
    }

}
